--[[
Author: Blus
Time:2020.11.09
Desc:main ui for pet
]]

require "Common/define"
require "Logic/Config"
require "Logic/PetManager"
require "Logic/FriendManager"
require "Common/functions"
require "Net/send_Msg"
local petMatingNode = require "View/UIPet/PetBreedNode"
local petMergeLevelUp = require "View/UIPet/Page_PetMergeLevelUp"

local UIPet = {}
HelperFunc.SetUIEnv(UIPet)
local this = UIPet

--综合
this.PetTabType = {
    Main = 0,
    Merge = 1,
    Mating = 2,
    Apply = 3,
    TryPart = 4,
}
this.hasInit = false
this.petTimer = nil

this.Btn_Back = nil
this.Btn_BGClose = nil
this.Txt_Title = nil
this.selectedPetItemIndex = 0
this.PetTabTypeController = nil
this.selectedPetTab = this.PetTabType.Main
this.Btn_Apply = nil;
--宠物
this.Tab_Pet = nil
this.Btn_PetPart = nil
this.Btn_FamilyTree = nil
this.Btn_Lock = nil
this.Btn_Follow = nil
this.Txt_TimesNumber = nil
this.Txt_PetCount = nil
this.List_Pet = nil
this.Model_Pet = nil
this.Txt_TimesWeak = nil
this.CurrentPetWeakTime = 0
this.WeakTimeController = nil
this.CheckBodyController = nil;
this.Btn_Help = nil
this.PetParts = {}; --宠物所有的部位合集
this.Txt_CurrentLevel2 = nil;--宠物进化等级
this.Txt_ExpNumber2 = nil;--宠物进化等级进度条数据
this.ProgressBar_Exp2 = nil;--宠物进化等级进度条
this.Btn_CurrentProperties = nil;--宠物加成查看按钮
this.currentPropertiesCtrl = nil;--宠物加成显示状态
this.currentPropertiesItems = {}--宠物加成item表
--融合
this.Tab_Merge = nil
this.Txt_CurrentLevel = nil
this.Txt_ExpNumber = nil
this.ProgressBar_Exp = nil
this.Img_TalentIcon = nil
this.Txt_TalentName = nil
this.Txt_TalentDisc = nil
this.TalentBuffTypeController = nil
this.talentSelected = 1
this.Btn_PetTalentBattleBuff = nil
this.Btn_PetTalentEcoBuff = nil
this.Btn_MergeConfirm = nil
this.Btn_ShowTalentLevel = nil
this.talents = {}
this.List_TalentBuff = nil
this.MaxLevelController = nil
this.Txt_NotTalent = nil
this.Btn_ShowTalentBonus = nil--打开牧场加成按钮
this.farmBonusCtrl = nil--牧场加成显隐
this.farmBonusItems = {}--牧场加成item表
this.Next_Info = nil;--宠物下一级显示
--拟变
this.Tab_Mating = nil
this.PetBreedNode = nil

--申请
this.PetMatingStatusType = {
    Idle = 0,
    CoolDown = 1,
}
this.Tab_Apply = nil
this.Btn_OrderByTime = nil
this.Btn_OrderByFriend = nil
this.Btn_RefuseAll = nil
this.Btn_MyApply = nil
this.List_OthersApply = nil
this.othersApplyList = {}
this.CheckApplyController = nil
this.idxApply = 1;
--试穿
this.TryPartTypeName = nil;
this.tryPartList = nil          --试穿组件列表
this.tryPartTypeId = 0;         --试穿的部位类型
this.tryPartGenes = {};         -- 当前试穿部件
this.tryPartListData = {};      --当前选择试穿的部位
this.saveTryPartBtnGroup = {}   --当前试穿的展示组123

this.saveTryPartBtn = nil;      -- 保存当前试穿按钮
this.delTryPartBtn = nil;       -- 删除当前试穿按钮
this.tryPartGroupIdx = 1;       --选择的组
this.tryPartCallBack = nil;     --保存后的参数回调
this.levelMax = nil;
this.clickMaskController = nil; --整个宠物页面屏蔽
--魂印
this.dataIndex = 0
this.attrTab = nil
this.attrSkillList = nil
this.attrSkillTip = nil
this.attrSkillDec = nil
this.attrHavePetCtrl = nil
this.attrGra = nil
this.attrmodelGO = nil
this.attrWra = nil
this.attrLvUp = nil
this.attrReset = nil
this.attrPetParts =  {}
this.attrPartLevel = nil
this.attrName = nil
this.attrBeVal = nil
this.attrAfVal = nil
this.sourceCtrl = nil
this.sourceUIobj = nil
this.btn_Source = nil
this.attrItemIcon = nil
this.attrItemNum = nil
this.choosePartCtrl = nil
this.clickPartNeedItemId= nil
this.petPartLvMaxCtrl = nil
this.petLvIcon = nil
this.petPartLvUpCtrl = nil
this.petPartLvUpList = nil
this.petPartLvUpBtn = nil
this.petPartLvShowCtrl = nil
this.petpartLvTip = nil
this.playUIMusic = false
this.beforeTabIndex = nil
this.clickTick = 0
function UIPet.Init()
    local name, packageName = getUIName(PanelNames.UIPet)
    panelMgr:ShowUI(name, packageName, this.OnCreate, Config.useLocalUI)
end

--定义控件
function UIPet.OnCreate(obj)
    if not this.hasInit then
        this.hasInit = true
        this.Btn_Back = obj:GetChild("Btn_Back")
        this.Btn_Back.onClick:Add(this.onCloseClick)
        this.Btn_BGClose = obj:GetChild("Btn_BGClose")
        this.Btn_BGClose.onClick:Add(this.onCloseClick)
        this.Txt_Title = obj:GetChild("Text_PetName")
        this.PetTabTypeController = obj:GetController("PetTabType")
        clickMaskController = obj:GetController("clickMask")
        this.btn_bgClose = obj:GetChild("bgClose")--申请背景
        this.btn_bgClose.onClick:Add(this.CloseApply)
        --宠物
        this.Tab_Pet = obj:GetChild("Tab_Pet")
        this.CheckBodyController = obj:GetController("CheckBody");
        this.Tab_Pet.onClick:Add(this.onShowPetMainTab)
        this.Txt_TimesNumber = obj:GetChild("Txt_TimesNumber")
        this.Txt_PetCount = obj:GetChild("Txt_PetCount")
        this.List_Pet = obj:GetChild("Comp_PetList"):GetChild("List_Pet")
        this.List_Pet.itemRenderer = this.renderPetListItem
        this.List_Pet.onClickItem:Add(this.onPetListItemClick)
        this.Btn_PetPart = obj:GetChild("Btn_PetPart")
        this.Btn_PetPart.onClick:Add(this.OnShowPartPage)
        this.Btn_FamilyTree = obj:GetChild("Btn_FamilyTree")
        this.Btn_FamilyTree.onClick:Add(this.OnShowFamilyPage)
        this.Btn_Lock = obj:GetChild("Btn_Lock")
        this.Btn_Lock.onClick:Add(this.OnChangePetLock)
        this.Btn_Follow = obj:GetChild("Btn_Follow")
        this.Btn_Follow.onClick:Add(this.OnFollow)
        this.Model_Pet = obj:GetChild("Model_Pet")
        this.Txt_TimesWeak = obj:GetChild("Txt_TimesWeak")
        this.WeakTimeController = obj:GetController("ifWeak")
        this.ClickWeak = obj:GetController("ClickWeak");
        this.Btn_PetCome = obj:GetChild("Btn_PetCome")
        this.Btn_PetCome.onClick:Add(this.onPetCome)
        this.Btn_Help = obj:GetChild("Btn_Help")
        this.Btn_Help.onClick:Add(this.onClickHelp)
        this.Txt_CurrentLevel2 = obj:GetChild("Txt_CurrentLevel2")
        this.Txt_ExpNumber2 = obj:GetChild("Txt_ExpNumber2")
        this.ProgressBar_Exp2 = obj:GetChild("ProgressBar_Exp2")
        this.Btn_Apply = obj:GetChild("Btn_Apply");
        this.Btn_Apply.onClick:Add(this.OnClickOpenFriendPetList);
        this.Btn_ShowTalentLevel = obj:GetChild("Btn_ShowTalentLevel");
        this.Btn_ShowTalentLevel.onClick:Add(this.onShowEvoTalentListPage);
        this.Btn_ShowAttr = obj:GetChild("Btn_ShowAttr");
        this.Btn_ShowAttr.onClick:Add(this.onShowTalentListPage)
        this.Btn_CurrentProperties = obj:GetChild("Btn_CurrentProperties");--查看当前属性
        this.Btn_CurrentProperties.onClick:Add(this.OnShowCurrentProperties);
        this.currentPropertiesCtrl = obj:GetController("CurrentProperties");--打开飞飞加成
        local attrCom = obj:GetChild("Page_PetEquip")
        attrSkillList = attrCom:GetChild("supskill")
        this.attrSkillTip = attrCom:GetChild("LevelTitle")
        this.attrSkillDec = attrCom:GetChild("SkillTips")
        this.attrHavePetCtrl = attrCom:GetController("IsPet")
        this.attrGra = attrCom:GetChild("Model_MyAddedPet")
        this.attrLvUp = attrCom:GetChild("Btn_MyAddedConfirm")
        this.attrReset = attrCom:GetChild("btn_reset")
        attrLvUp.onClick:Add(this.AttrUp)
        attrReset.onClick:Add(this.AttrReset)
        for i=1,PetManager.PetPart.Ornament do
            this.attrPetParts[i] = {}
            this.attrPetParts[i].obj = attrCom:GetChild("Btn_MyPetBody"..i)
            this.attrPetParts[i].ctrl = this.attrPetParts[i].obj:GetController("ShowType")
            this.attrPetParts[i].lv = this.attrPetParts[i].obj:GetChild("Level")
            this.attrPetParts[i].anim = this.attrPetParts[i].obj:GetChild("zyxt_effect").wrapTarget
            this.attrPetParts[i].obj.onClick:Add(function()
                this.ClickAttrPart(i,true)
            end)
        end
        this.attrPartLevel = attrCom:GetChild("Equip_level")
        this.attrName = attrCom:GetChild("Equip_att")
        this.attrBeVal = attrCom:GetChild("Equip_before")
        this.attrAfVal = attrCom:GetChild("Equip_after")
        this.sourceCtrl = attrCom:GetController("showSource")
        this.sourceUIobj = attrCom:GetChild("source")
        this.btn_Source = attrCom:GetChild("btnSource")
        this.btn_Source.onClick:Add(this.GoSource)
        this.attrItemIcon = attrCom:GetChild("Img_coin03")
        this.attrItemNum = attrCom:GetChild("Text_coin03")
        this.choosePartCtrl = attrCom:GetController("c1")
        this.petPartLvMaxCtrl = attrCom:GetController("lvMax")
        this.petLvIcon = attrCom:GetChild("Img_coin04")
        this.petPartLvUpCtrl = obj:GetController("LevelUp")
        this.petPartLvUpList = obj:GetChild("skillList")
        this.petPartLvUpBtn = obj:GetChild("BgClose")
        this.petPartLvShowCtrl = attrCom:GetController("lvShow")
        this.petpartLvTip = attrCom:GetChild("Tips02")
        this.petPartLvUpBtn.onClick:Add(function()
            this.petPartLvUpCtrl.selectedIndex = 0
        end)
        this.ctrlNoPet = obj:GetController("NoPet")
        if #PetManager.PetInfoList == 0 then
            this.ctrlNoPet.selectedIndex = 1
            obj:GetChild("PetListEmpty1"):GetChild("title").text = getLanguage("PetMain_NoPet")
            obj:GetChild("PetListEmpty2"):GetChild("title").text = getLanguage("PetFittingRoom_NoPet")
        else
            this.ctrlNoPet.selectedIndex = 0
        end
        this.currentPropertiesItems = {}
        local itemCount = 1;
        while true do
            local item = obj:GetChild("PetBonus_" .. itemCount);
            if item ~= nil then
                table.insert(this.currentPropertiesItems, item);
            else
                break ;
            end
            itemCount = itemCount + 1;
        end
        this.Tab_Merge = obj:GetChild("Tab_Merge")
        this.petMergeLevelUpNode = obj:GetChild("Page_PetMergeLevelUp");
        this.Tab_Merge.onClick:Add(this.onShowMergeTab)
        this.petMergeLevelUp = petMergeLevelUp.New();
        this.petMergeLevelUp:Init(this.petMergeLevelUpNode)
        this.Txt_CurrentLevel = obj:GetChild("Txt_CurrentLevel")
        this.Txt_ExpNumber = obj:GetChild("Txt_ExpNumber")
        this.ProgressBar_Exp = obj:GetChild("ProgressBar_Exp")
        this.Img_TalentIcon = obj:GetChild("Img_TalentIcon")
        this.Txt_TalentName = obj:GetChild("Txt_TalentName")
        this.Txt_TalentDisc = obj:GetChild("Txt_TalentDisc")
        this.Txt_NotTalent = obj:GetChild("Txt_NotTalent")
        this.MaxLevelController = obj:GetController("maxlevel")
        obj:GetChild("Txt_Title").text = getLanguage("PetMerge_Title")
        obj:GetChild("Txt_NextActive").text = getLanguage("PetMerge_NextLevelContent")
        obj:GetChild("Txt_TalentBonus").text = getLanguage("PetMerge_TalentBonus")
        this.TalentBuffTypeController = obj:GetController("TalentBuffType")
        this.Btn_PetTalentBattleBuff = obj:GetChild("Btn_PetTalentBattleBuff")
        this.Btn_PetTalentBattleBuff.onClick:Add(this.onTalentBattleBuffClick)
        this.Btn_PetTalentEcoBuff = obj:GetChild("Btn_PetTalentEcoBuff")
        this.Btn_PetTalentEcoBuff.onClick:Add(this.onTalentEconomicalBuffClick)
        this.List_TalentBuff = this.petMergeLevelUpNode:GetChild("List_TalentBuff")
        this.List_TalentBuff.itemRenderer = this.renderTalentBuffItem
        this.Btn_MergeConfirm = obj:GetChild("Btn_MergeConfirm")
        this.Btn_MergeConfirm.onClick:Add(this.onMergeClick)
        this.Btn_ShowTalentBonus = obj:GetChild("Btn_ShowTalentBonus")
        this.Btn_ShowTalentBonus.onClick:Add(this.OnShowFarmBonus);
        this.farmBonusCtrl = obj:GetController("FarmBonus");
        this.farmBonusItems = {};
        itemCount = 1;
        while true do
            local item = obj:GetChild("FrameBonus_" .. itemCount);
            if item ~= nil then
                table.insert(this.farmBonusItems, item);
            else
                break ;
            end
            itemCount = itemCount + 1;
        end
        --拟变
        this.Tab_Mating = obj:GetChild("Tab_Mating")
        this.Tab_Mating.onClick:Add(this.onShowMatingTab)
        this.PetBreedNode = petMatingNode.New()
        this.PetBreedNode:Init(obj:GetChild("Panel_Mating"))
        --申请
        this.Tab_Apply = obj:GetChild("Tab_Apply")
        this.Tab_Apply.onClick:Add(this.onTryPart)
        --申请列表下一页按钮
        this.nextPageBtn = obj:GetChild("btnNext")
        this.nextPageBtn.onClick:Add(this.applyTabNext);
        --申请列表上一页按钮
        this.lastPageBtn = obj:GetChild("btnLast")
        this.lastPageBtn.onClick:Add(this.applyTabLast);
        this.Btn_OrderByFriend = obj:GetChild("Btn_OrderByFriend")
        this.Btn_OrderByFriend.onClick:Add(this.onClickOrderByFriend)
        this.Btn_RefuseAll = obj:GetChild("Btn_RefuseAll")
        this.Btn_RefuseAll.onClick:Add(this.onClickRefuseAll)
        this.List_OthersApply = obj:GetChild("List_OthersApply")
        this.levelMaxController = obj:GetController("LevelMax")
        this.Btn_FriendApply = obj:GetChild("Btn_FriendApply");
        this.Btn_FriendApply.onClick:Add(this.onShowApplyTab)
        this.Updatelist()
        this.Btn_MyApply = obj:GetChild("Btn_MyApply")
        this.Btn_MyApply.onClick:Add(this.onShowMyApplyPage)
        this.CheckApplyController = obj:GetController("ifNoApply")
        obj:GetChild("n72").text = getLanguage("PetApply_Applicant")
        obj:GetChild("n73").text = getLanguage("PetApply_ApplyTarget")
        this.PetParts = {}
        this.PetPartsShow = {}
        for i = 1, 13 do
            local idx = i >= 10 and i or "0" .. i;
            local item = obj:GetChild("Btn_MyPetBodyShow" .. idx);
            table.insert(this.PetPartsShow, item);
        end
        --试穿
        for i = 1, 13 do
            local idx = i >= 10 and i or "0" .. i;
            local item = obj:GetChild("Btn_MyPetBody" .. idx);
            table.insert(this.PetParts, item);
        end
        this.saveTryPartBtnGroup = {}
        for i = 1, 3 do
            local btn = obj:GetChild("btnPlan" .. i);
            btn.onClick:Clear()
            btn.onClick:Add(function()
                this.tryPartGroupIdx = i;
                this.clickTryPartGroup();
            end)
            table.insert(this.saveTryPartBtnGroup, btn);
        end
        this.saveTryPartBtn = obj:GetChild("btnSave");
        this.saveTryPartBtn.onClick:Add(this.saveTryPartData)
        this.delTryPartBtn = obj:GetChild("btnDelete");
        this.delTryPartBtn.onClick:Add(this.deleteTryPartData)
        this.tryPartList = obj:GetChild("List_ChangePart");
        this.tryPartList.itemRenderer = this.rendererTryPartItem;
        this.tryPartTypeName = obj:GetChild("Txt_TryPartName");
        this.attrTab = obj:GetChild("Tab_PetEqupi")
        this.attrTab.onClick:Add(function()
            if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.PetPartAttr, true, this.attrTab) then
                this.sourceCtrl.selectedIndex = 0
                FireEvent(Config.EventType.PetPartRed)
                PetHandler.ReqPartListInfo()
            else
                this.PetTabTypeController.selectedIndex = beforeTabIndex
            end
        end)
        this.initPetModel()
    end
    this.OnEnable()
    this.addEvent()
    this.onShowPetMainTab()
    this.setTimer()
    UIRedDots.addViewListen(PanelNames.UIPet, "UIPet" .. Tab_Apply.name, Btn_FriendApply, Config.RedDotsType.PetMating);
    UIRedDots.addViewListen(PanelNames.UIPet, "UIPet" .. Tab_Mating.name, Tab_Mating, Config.RedDotsType.PetMating);
    UIRedDots.addViewListen(PanelNames.UIPet, "UIPet" .. attrTab.name, attrTab, Config.RedDotsType.PetPartUp);
    logicMgr.FuncOpenManager.addStatusCtr(PanelNames.UISupSelect, Config.FuncOpenType.PetPartAttr, this.attrTab.name, this.attrTab);
    friendHandler.ReqFriendData()
end
function this.OnEnable()
    this.needShowHeadMenu = nil;
    if isOpenUI(PanelNames.UIHeadMenu) then
        this.needShowHeadMenu = true;
        closeUI(PanelNames.UIHeadMenu);
    end
end

function this.OnDisable()
    CloseEvent(Config.EventType.SaveTryPart, this.saveTryPartCallBack)
    CloseEvent(Config.EventType.RefreshPetList, this.RefreshPetList)
    CloseEvent(Config.EventType.RefreshPetLock, this.RefreshPetLock)
    CloseEvent(Config.EventType.RefreshPetFollow, this.RefreshPetFollow)
    CloseEvent(Config.EventType.RefreshMergePet, this.onShowMergeTab)
    CloseEvent(Config.EventType.RefreshPetCancelMating, this.Updatelist)
    CloseEvent(Config.EventType.RefreshOthersApplyList, this.onShowApplyTab)
    CloseEvent(Config.EventType.RefreshOthersApplyList, this.changeClickMask)
    CloseEvent(Config.EventType.PetPartsAttrUpdate,this.FreshSkill)
    CloseEvent(Config.EventType.PetPartAttrUpLv,this.UpLvFresh)

    utimer.remove(this.petTimer)
    this.petTimer = nil
    UIRedDots.removeViewEvent(PanelNames.UIPet)
    logicMgr.FuncOpenManager.removeStatusCtr(PanelNames.UIPet);
    this.removePetModel()
    this.petMergeLevelUp:RemoveEvent();
    this.PetBreedNode:RemoveEvent()
    this.removeEvent()
    this.hasInit = false
    if this.attrmodelGO then
        destroy(this.attrmodelGO)
        this.attrmodelGO = nil
    end
    if this.attrWra then
        this.attrWra:Dispose()
        this.attrWra = nil
    end
end

function this.OnDestroy()
end

function UIPet.addEvent()
    this.petMergeLevelUp:AddEvent();
    this.PetBreedNode:AddEvent()
    this.PetTabTypeController.onChanged:Add(function()
        if this.selectedPetTab ~= this.PetTabType.Mating then
            if #PetManager.PetInfoList == 0 and this.PetTabTypeController.selectedIndex == this.PetTabType.Main then
                this.ctrlNoPet.selectedIndex = 1
            end

            PetManager.TemplatePetId = 0;
            PetManager.MutatePetId = 0;
        end
    end)
    ListenEvent(Config.EventType.SaveTryPart, this.saveTryPartCallBack)
    ListenEvent(Config.EventType.RefreshPetList, this.RefreshPetList)
    ListenEvent(Config.EventType.RefreshPetLock, this.RefreshPetLock)
    ListenEvent(Config.EventType.RefreshPetFollow, this.RefreshPetFollow)
    ListenEvent(Config.EventType.RefreshMergePet, this.onShowMergeTab)
    ListenEvent(Config.EventType.RefreshPetCancelMating, this.Updatelist)
    ListenEvent(Config.EventType.RefreshOthersApplyList, this.onShowApplyTab)
    ListenEvent(Config.EventType.RefreshOthersApplyList, this.changeClickMask)
    ListenEvent(Config.EventType.PetPartsAttrUpdate,this.FreshSkill)
    ListenEvent(Config.EventType.PetPartAttrUpLv,this.UpLvFresh)
end

function UIPet.Updatelist()
    this.othersApplyList = {}
    this.othersApplyList = PetManager.applies
    this.List_OthersApply.itemRenderer = this.renderOthersApplyItem
    this.List_OthersApply.onClickItem:Clear()
    FireEvent(Config.EventType.RefreshOthersApplyList)
end

function UIPet.removeEvent()
    this.PetTabTypeController.onChanged:Clear();
    this.Btn_Back.onClick:Clear()
    this.Btn_BGClose.onClick:Clear()
    this.Btn_Apply.onClick:Clear();
    this.Btn_ShowTalentLevel.onClick:Clear();
    this.Tab_Pet.onClick:Clear()
    this.List_Pet.onClickItem:Remove(this.onPetListItemClick)
    this.Btn_PetPart.onClick:Clear()
    this.Btn_FamilyTree.onClick:Clear()
    this.Btn_Lock.onClick:Clear()
    this.Btn_Follow.onClick:Clear()
    this.Btn_CurrentProperties.onClick:Clear()
    this.Tab_Merge.onClick:Clear()
    this.Btn_PetTalentBattleBuff.onClick:Clear()
    this.Btn_PetTalentEcoBuff.onClick:Clear()
    this.Btn_MergeConfirm.onClick:Clear()
    this.Btn_ShowTalentLevel.onClick:Clear()
    this.Btn_ShowTalentBonus.onClick:Clear()
    this.Tab_Mating.onClick:Clear()
    this.Tab_Apply.onClick:Clear()
    this.Btn_RefuseAll.onClick:Clear()
    this.Btn_MyApply.onClick:Clear()
    this.attrTab.onClick:Clear()
    this.btn_Source.onClick:Clear()
    attrLvUp.onClick:Clear()
    attrReset.onClick:Clear()
    for _,v in pairs(this.attrPetParts) do
        v.obj.onClick:Clear()
    end
    attrSkillList.scrollPane.onScroll:Remove(this.DoSpecial)
    attrSkillList.scrollPane.onScrollEnd:Remove(this.onScrollEnd)
    attrSkillList.onClickItem:Remove(this.scrollToItem)
end

function UIPet.CloseApply()
    if this.selectedPetTab == this.PetTabType.Apply then
        this.selectedPetTab = this.PetTabType.Mating
        this.PetTabTypeController:SetSelectedIndex(this.selectedPetTab)
    end
end

-- 综合 Start
function UIPet.onCloseClick()
    PetManager.TemplatePetId = 0
    PetManager.MutatePetId = 0
    this.OnDisable()
    closeUI(PanelNames.UIPet)
    logicMgr.HeroManager.UpdateAllAttr()
    partnerHandler.ReqHeroPower(0)
    FireEvent(Config.EventType.ReFreshHeroPower)
    if this.needShowHeadMenu then
        showUI(PanelNames.UIHeadMenu);
        this.needShowHeadMenu = nil;
    end
end

function UIPet.changeClickMask(is)
    this.clickMaskController:SetSelectedIndex(is and 1 or 0)
end

function UIPet.OnClickOpenFriendPetList()
    this.PetBreedNode:RemoveEvent()
    PetManager.TemplatePetId = 0;
    PetManager.MutatePetId = 0;
    PetBreedNode:RefreshMatingPage()
    showUI(PanelNames.UIPetFriendList, function()
        this.PetBreedNode:AddEvent()
    end);
end

function this.setTimer()
    if this.petTimer == nil then
        this.petTimer = utimer.timeCall(function()
            PetManager.PetMatingCountDown()
            if this.selectedPetTab == this.PetTabType.Apply then
            elseif this.selectedPetTab == this.PetTabType.Main then
                if this.CurrentPetWeakTime > 0 then
                    this.CurrentPetWeakTime = this.CurrentPetWeakTime - 1
                    this.Txt_TimesWeak.text = TimeFormatToHHMMSS(this.CurrentPetWeakTime)
                    if this.CurrentPetWeakTime < 1 then
                        this.WeakTimeController:SetSelectedIndex(0)
                        this.ClickWeak:SetSelectedIndex(0)
                    end
                end
            end

        end, 1000, -1)
    end
end
--宠物界面 Start
function this.initPetModel()
    if this.mainPetModelInfo == nil then
        this.mainPetModelInfo = {}
    end
    if this.petListModelInfo == nil then
        this.petListModelInfo = {}
    end
    if this.petAppliesModelInfo == nil then
        this.petAppliesModelInfo = {}
    end
end
function this.removePetModel()
    this.removeMainPetModel()
    if this.petListModelInfo then
        for index, _ in pairs(this.petListModelInfo) do
            this.removePetListModelByIndex(index)
        end
    end
    if this.petAppliesModelInfo then
        for applyIndex, _ in pairs(this.petAppliesModelInfo) do
            this.removePetAppliesModelByIndex(applyIndex)
        end
    end
end

function this.removePetListModelByIndex(index)
    --删除model本身
    if this.petListModelInfo[index].modelGO then
        destroyImmediate(this.petListModelInfo[index].modelGO)
    end
    this.petListModelInfo[index].modelGO = nil
    this.petListModelInfo[index].parentGO = nil
    this.petListModelInfo[index].petId = nil

end
function this.removePetAppliesModelByIndex(index)
    if this.petAppliesModelInfo[index].modelGO then
        destroyImmediate(this.petAppliesModelInfo[index].modelGO)
    end
    this.petAppliesModelInfo[index].modelGO = nil
    this.petAppliesModelInfo[index].parentGO = nil
    this.petAppliesModelInfo[index].petId = nil

end

function this.onShowPetMainTab()
    beforeTabIndex = this.PetTabTypeController.selectedIndex
    this.selectedPetTab = this.PetTabType.Main
    this.PetTabTypeController:SetSelectedIndex(this.selectedPetTab)
    local _currentPetInfo = PetManager.GetPetInfoByPetId(PetManager.CurrentPetId)
    if _currentPetInfo then
        this.Txt_TimesNumber.text = tostring(_currentPetInfo.matingCount)
    end
    this.CheckBodyController:SetSelectedIndex(0);
    this.Txt_PetCount.text = string.format("%d/%d", #PetManager.PetInfoList, PetManager.MaxPetCount)
    this.List_Pet.numItems = #PetManager.PetInfoList
    this.showMainPetModel()
    this.refreshPetEvoLevelProgress();
end

function this.refreshPetEvoLevelProgress()
    this.Txt_CurrentLevel2.text = PetManager.EvoLevel;
    local curEvoLevelCfg = G.dataTable["t_elvesevolevel"][tostring(PetManager.EvoLevel)]
    local nextEvoLevelCfg = G.dataTable["t_elvesevolevel"][tostring(PetManager.EvoLevel + 1)]
    local sumExp = 0;
    for i = 1, PetManager.EvoLevel do
        local cfg = G.dataTable["t_elvesevolevel"][tostring(i)]
        sumExp = sumExp + cfg["f_Exp"];
    end
    local curExp = PetManager.EvoLevelExp;
    if not nextEvoLevelCfg then
        this.Txt_ExpNumber2.text = "Max";
        this.ProgressBar_Exp2.value = 100;
    else
        this.ProgressBar_Exp2.value = (curExp / nextEvoLevelCfg["f_Exp"]) * 100;
        this.Txt_ExpNumber2.text = curExp .. "/" .. nextEvoLevelCfg["f_Exp"];
    end
end

function this.renderPetListItem(index, obj)
    local petInfo = PetManager.GetPetInfoByIndex(index + 1)
    if petInfo.petId == PetManager.CurrentPetId then
        this.selectedPetItemIndex = index
        obj.selected = true
        this.Txt_Title.text = petInfo.petName
        local _touchable = not petInfo.IsFollowStatus
        this.Btn_Follow.touchable = _touchable
        this.Btn_Follow.enabled = _touchable
        this.Btn_Lock.selected = petInfo.IsLocked
        --"锁定"
        local _lockStr = getLanguage("PetMain_Btn_Lock")
        if petInfo.IsLocked then
            _lockStr = getLanguage("PetMain_Btn_Unlock") --"解锁"
        end
        this.Btn_Lock:GetChild("title").text = _lockStr
        local _followStr = getLanguage("PetMain_Btn_Follow") --"跟随"
        if petInfo.IsFollowStatus then
            _followStr = getLanguage("PetMain_Btn_Following") --跟随中
        end
        this.Btn_Follow:GetChild("title").text = _followStr

        this.CurrentPetWeakTime = petInfo.matingEndTime - HelperFunc.GetServerTime()
        local _weakTimeIndex = 0
        if this.CurrentPetWeakTime > 0 then
            _weakTimeIndex = 1
            this.Txt_TimesWeak.text = TimeFormatToHHMMSS(this.CurrentPetWeakTime)
        else
            this.CurrentPetWeakTime = 0
        end
        this.ClickWeak:SetSelectedIndex(0)
        this.WeakTimeController:SetSelectedIndex(_weakTimeIndex)

    else
        obj.selected = falsePetSelect
    end
    local _selectedIndex = PetManager.GetPetItemType(petInfo)
    obj:GetController("type"):SetSelectedIndex(_selectedIndex)
    obj:GetController("Lock"):SetSelectedIndex(petInfo.IsLocked and 0 or 1)
    obj:GetController("follow"):SetSelectedIndex(petInfo.IsFollowStatus and 0 or 1)
    --宠物底图
    local _petMutationLevel = PetManager.GetMutationLevel(petInfo.genes)
    obj:GetController("level"):SetSelectedIndex(_petMutationLevel - 1)
    obj:GetChild("frame").url = PetManager.GetMutationLevelFrameIcon(_petMutationLevel)
    --显示宠物模型
    if this.petListModelInfo[index + 1] == nil then
        this.petListModelInfo[index + 1] = {}
    end
    local _parentGO = obj:GetChild("Model_Pet")
    if this.petListModelInfo[index + 1].modelGO and this.petListModelInfo[index + 1].petId == petInfo.petId then
        PetManager.PetModelRefresh(this.petListModelInfo[index + 1], petInfo.genes, false)
    else
        this.removePetListModelByIndex(index + 1)
        resMgr:LoadModelPrefab(PetManager.PetModelPrefab, function(go)
            local n_go = newObject(go)
            local com = n_go:GetComponent("SkeletonGraphic")
            if n_go and com then
                com.material:SetFloat("_StencilComp", 3)
                com.material:SetFloat("_Stencil", 1);
            end
            this.petListModelInfo[index + 1].modelGO = n_go
            this.petListModelInfo[index + 1].parentGO = _parentGO
            local _modelWrapper = this.petListModelInfo[index + 1].modelWrapper
            this.petListModelInfo[index + 1].modelWrapper = GoWrapper.New()
            this.petListModelInfo[index + 1].petId = petInfo.petId
            PetManager.PetModelFirstSet(this.petListModelInfo[index + 1], petInfo.genes, false, Vector3.New(0, 0, 0), Vector3.New(0.55, 0.55, 1), 3)
            if _modelWrapper then
                _modelWrapper:Dispose()
            end
        end)
    end
end

function this.onPetListItemClick(context)
    local obj = context.data
    local index = this.List_Pet:GetChildIndex(obj)
    this.selectedPetItemIndex = index
    local petInfo = PetManager.GetPetInfoByIndex(index + 1)
    PetManager.CurrentPetId = petInfo.petId
    this.Txt_Title.text = petInfo.petName
    this.Txt_TimesNumber.text = tostring(petInfo.matingCount)
    local _touchable = not petInfo.IsFollowStatus
    this.Btn_Follow.touchable = _touchable
    this.Btn_Follow.enabled = _touchable
    this.Btn_Lock.selected = petInfo.IsLocked
    local _lockStr = getLanguage("PetMain_Btn_Lock")
    if petInfo.IsLocked then
        _lockStr = getLanguage("PetMain_Btn_Unlock")
    end
    this.Btn_Lock:GetChild("title").text = _lockStr
    local _followStr = getLanguage("PetMain_Btn_Follow") --"跟随"
    if petInfo.IsFollowStatus then
        _followStr = getLanguage("PetMain_Btn_Following") --跟随中
    end
    this.Btn_Follow:GetChild("title").text = _followStr
    this.CurrentPetWeakTime = petInfo.matingEndTime - HelperFunc.GetServerTime()
    local _weakTimeIndex = 0
    if this.CurrentPetWeakTime > 0 then
        _weakTimeIndex = 1
        this.Txt_TimesWeak.text = TimeFormatToHHMMSS(this.CurrentPetWeakTime)
    else
        this.CurrentPetWeakTime = 0
    end
    this.ClickWeak:SetSelectedIndex(0)
    this.WeakTimeController:SetSelectedIndex(_weakTimeIndex)
    this.showMainPetModel()
end
function this.RefreshPetList()
    if this.selectedPetTab == this.PetTabType.Main then
        this.onShowPetMainTab()
    end
end
function this.onPetCome()
    showUI(PanelNames.UIPetBanner, this.onCloseClick);
end
function this.onClickHelp()
    local txts = {};
    txts["title"] = "HelpTitle29";
    txts["des"] = "HelpDes29";
    txts["story"] = "FunctionStory1090";
    showUI(PanelNames.CommonTips, txts)
end
--锁定
function this.OnChangePetLock()
    local _petInfo = PetManager.GetPetInfoByIndex(this.selectedPetItemIndex + 1)
    if _petInfo then
        if _petInfo.IsLocked then
            PetHandler.ReqUnlockPet(PetManager.CurrentPetId)
        else
            PetHandler.ReqLockPet(PetManager.CurrentPetId)
        end
    end
end
function this.RefreshPetLock()
    this.onShowPetMainTab()
end
--跟随
function this.OnFollow()
    local petInfo = PetManager.GetPetInfoByIndex(this.selectedPetItemIndex + 1)
    if #PetManager.applies > 0 then
        --提示玩家处理拟变申请
        UISysTips.AddMsg(getLanguage("PetApply_Pseudomorphism"));
        return ;
    elseif petInfo.IsMatingStatus then
        --申请拟变的状态不能跟随
        UISysTips.AddMsg(getLanguage("PetApply_QuasiVariational"));
        return ;
    else
        if petInfo and not petInfo.IsFollowStatus then
            local _followPetInfo = PetManager.GetFollowPetInfo()
            if _followPetInfo  and _followPetInfo.petId then
                PetHandler.ReqCancelPetFollow(_followPetInfo.petId)
            end
            PetHandler.ReqPetFollow(PetManager.CurrentPetId)
        end
    end
end

function this.RefreshPetFollow()
    this.onShowPetMainTab()
end

function UIPet.OnShowPartPage()
    local _petInfo = PetManager.GetPetInfoByPetId(PetManager.CurrentPetId)
    if _petInfo then
        if this.CheckBodyController.selectedIndex == 0 then
            this.CheckBodyController:SetSelectedIndex(0);
        else
            this.CheckBodyController:SetSelectedIndex(1);
        end
    end
end

function UIPet.OnShowFamilyPage()
    local _petInfo = PetManager.GetPetInfoByPetId(PetManager.CurrentPetId)
    if _petInfo then
        showUI(PanelNames.Page_PetMainFamilyTree)
    end
end
--显示当前宠物加成
function UIPet.OnShowCurrentProperties()
    if logicMgr.PetManager.EvoLevel == 0 then
        --没有加成
        this.Btn_CurrentProperties.selected = false;
        UISysTips.AddMsg(getLanguage("PetApply_NotActive"))
        return ;
    end
    if this.currentPropertiesCtrl.selectedIndex == 0 then
        this.RefreshShowCurrentProperties()
    else
        this.currentPropertiesCtrl.selectedIndex = 0;
    end
end

function UIPet.RefreshShowCurrentProperties()
    if logicMgr.PetManager.EvoLevel == 0 then
        return ;
    end
    this.currentPropertiesCtrl.selectedIndex = 1;
    local petShowCfg = {}
    if logicMgr.PetManager.EvoLevel ~= 0 then
        petShowCfg = decodeJsonStrToTabel(G.dataTable["t_elvesevolevel"][tostring(logicMgr.PetManager.EvoLevel)]["f_BattleTalentDesc"]);
    end
    for i = 1, #this.currentPropertiesItems do
        local item = this.currentPropertiesItems[i]
        if petShowCfg[i] then
            item.visible = true;
            item:GetChild("info").text = getLanguage(petShowCfg[i]);
        else
            item.visible = false;
        end
    end
end
-- 融合 Start
function this.onShowMergeTab()
    this.selectedPetTab = this.PetTabType.Merge
    this.PetTabTypeController:SetSelectedIndex(this.selectedPetTab)
    if PetManager.petLv == PetManager.MaxPetLevel then
        this.levelMaxController.selectedIndex = 1;
    else
        this.levelMaxController.selectedIndex = 0;
    end
    this.onShowNextActive()
    this.RefreshMergeTalent()
    petMergeLevelUp:clearMergeList();
    petMergeLevelUp:showList(true);
end
--融合主界面-下一级可激活
function this.onShowNextActive()
    if PetManager.petLv == PetManager.MaxPetLevel then
        this.MaxLevelController:SetSelectedIndex(1)
        return
    end
    this.MaxLevelController:SetSelectedIndex(0)
    local _nextLv = PetManager.petLv + 1
    if _nextLv > PetManager.MaxPetLevel then
        _nextLv = PetManager.MaxPetLevel
    end
    local _nextTalent = G.dataTable["t_elvestalent"][tostring(_nextLv)]
    this.Txt_TalentName.text = getLanguage(_nextTalent.f_TalentName)
    this.Txt_TalentDisc.text = getLanguage(_nextTalent.f_TalentDesc)
    this.Img_TalentIcon.url = PetManager.GetTalentBuffIcon(_nextTalent.f_TalentBuffType)
end
--融合主界面-天赋加成
function this.onTalentBattleBuffClick()
    this.talentSelected = PetManager.TalentBuffType.BattleBuff
    this.RefreshMergeTalent()
end
function this.onTalentEconomicalBuffClick()
    this.talentSelected = PetManager.TalentBuffType.EcoBuff
    this.RefreshMergeTalent()
end

function UIPet.RefreshMergeTalent()
    this.talents = {}
    this.TalentBuffTypeController:SetSelectedIndex(this.talentSelected - 1)
    local talentsCfg = G.dataTable["t_elvestalent"];
    for i = 1, table.getn(talentsCfg) do
        table.insert(this.talents, { state = PetManager.petLv >= i and 1 or 0, value = talentsCfg[tostring(i)] })
    end
    this.List_TalentBuff.numItems = #this.talents

    local _notTalent = ""
    if #this.talents == 0 then
        _notTalent = getLanguage("PetMerge_Txt_NotTalent") --"尚无天赋加成"
    end
    this.Txt_NotTalent.text = _notTalent
end

function UIPet.renderTalentBuffItem(index, obj)
    local data = this.talents[index + 1];
    local controller = obj:GetController("lock");
    if data.state == 1 then
        controller.selectedIndex = 0;
    else
        controller.selectedIndex = 1;
    end
    obj:GetChild("Text_BuffTips").text = getLanguage(data.value.f_TalentDesc);
    obj:GetChild("Text_BuffLevel").text = data.value.f_TalentId;
    obj:GetChild("Text_BuffNum").text = ""
end
--按钮(融合、天赋列表)
function UIPet.onMergeClick()
    if PetManager.petLv ~= PetManager.MaxPetLevel then
        showUI(PanelNames.Page_PetMergeLevelUp)
    end
end

function this.onShowTalentListPage()
    showUI(PanelNames.Page_PetMergeTalentList, 1)
end
function this.onShowEvoTalentListPage()
    showUI(PanelNames.Page_PetMergeTalentList, 0)
end
--打开牧场加成
function UIPet.OnShowFarmBonus()
    if logicMgr.PetManager.petLv == 0 then
        --没有加成
        this.Btn_ShowTalentBonus.selected = false;
        UISysTips.AddMsg(getLanguage("PetApply_NotActive"))
        return ;
    end
    if this.farmBonusCtrl.selectedIndex == 0 then
        this.farmBonusCtrl.selectedIndex = 1;
        UIPet.refreshShowFarmBonus();
    else
        this.farmBonusCtrl.selectedIndex = 0;
    end
end

function UIPet.refreshShowFarmBonus()
    if logicMgr.PetManager.petLv == 0 then
        return ;
    end
    local petShowCfg = {}
    petShowCfg = decodeJsonStrToTabel(G.dataTable["t_elvesmerge"][tostring(logicMgr.PetManager.petLv)]["f_EcoBuffId"]);
    for i = 1, #this.farmBonusItems do
        local item = this.farmBonusItems[i]
        if petShowCfg[i] then
            item.visible = true;
            local dec = G.dataTable["t_ecobuff"][tostring(petShowCfg[i])]["f_BuffDesc"]
            item:GetChild("info").text = getLanguage(dec);
        else
            item.visible = false;
        end
    end
end
--拟变 Start
function UIPet.onShowMatingTab()
    this.selectedPetTab = this.PetTabType.Mating
    this.PetTabTypeController:SetSelectedIndex(this.selectedPetTab)
    PetBreedNode:removeTemplateModel()
    PetBreedNode:removeMutateModel()
    PetBreedNode:RefreshMatingPage()
end

--拟变 End

--申请 Start
function this.onShowApplyTab()
    if this.selectedPetTab == this.PetTabType.Merge then
        return
    end
    this.idxApply = 1;
    this.selectedPetTab = this.PetTabType.Apply
    this.PetTabTypeController:SetSelectedIndex(this.selectedPetTab)
    this.othersApplyList = {}
    this.othersApplyList = PetManager.applies
    this.onClickOrderByTime()
    this.showOthersApply()
end

function this.applyTabNext()
    this.idxApply = this.idxApply + 5;
    local num = 5;

    if #this.othersApplyList - this.idxApply < 5 then
        num = #this.othersApplyList - this.idxApply;
        nextPageBtn.visible = false;
    else
        nextPageBtn.visible = true;
    end
    lastPageBtn.visible = true;
    this.List_OthersApply.numItems = num

end

function this.applyTabLast()
    this.idxApply = this.idxApply - 5;
    if this.idxApply <= 1 then
        lastPageBtn.visible = false;
    end
    nextPageBtn.visible = true;
    local num = 5;
    this.List_OthersApply.numItems = num

end

function this.showOthersApply()
    local num = #this.othersApplyList
    lastPageBtn.visible = false;
    nextPageBtn.visible = false;

    if #this.othersApplyList > 5 then
        num = 5;
        nextPageBtn.visible = true;
    end
    this.List_OthersApply.numItems = num

    local _typeIndex = 0
    local _touchable = true
    if #this.othersApplyList == 0 then
        _typeIndex = 1
        _touchable = false
    end
    this.CheckApplyController:SetSelectedIndex(_typeIndex)
end
function this.renderOthersApplyItem(index, obj)
    local _applyIndex = idxApply + index
    local _applyInfo = this.othersApplyList[_applyIndex]
    --申请人
    local head = obj:GetChild("head")
    obj:GetChild("Txt_PlayerName").text = _applyInfo.fromPlayerName
    head:GetChild("head"):GetChild("HeadIcon").url = EnumConst.AtlasPath.ICONAtlas .. dataTable.getRow("t_hero", _applyInfo.fromPlayerPic)["f_HeroIcon"];
    head:GetChild("frame").url = EnumConst.AtlasPath.ICONAtlas .. _applyInfo.fromPlayerPicFrame;
    local btn_ApplyFri = obj:GetChild("btn_ApplyFri")
    btn_ApplyFri.onClick:Clear();
    btn_ApplyFri.onClick:Add(this.onClickConfirm);
    local btn_RefuseFri = obj:GetChild("btn_RefuseFri")
    btn_RefuseFri.onClick:Clear();
    btn_RefuseFri.onClick:Add(this.onClickRefuse);

    local _applyLastTime = _applyInfo.endTime - HelperFunc.GetServerTime()
    if _applyLastTime < 0 then
        _applyLastTime = 0
    end
    obj:GetChild("Txt_ApplyLastTime").text = TimeFormatToHHMMSS(_applyLastTime)
    --我的宠物-作为模板
    local _selectedIndex = this.PetMatingStatusType.Idle
    local _lastMatingEndTime = ""
    local _matingEndTime = PetManager.GetPetMatingEndTime(_applyInfo.templatePetInfo.petId)
    _selectedIndex = this.PetMatingStatusType.Idle
    obj:GetChild("Txt_IsIdle").text = getLanguage("PetApply_MyPetIdle") --"空闲"
    obj:GetController("time"):SetSelectedIndex(_selectedIndex)
    obj:GetChild("Txt_MatingEndTime").text = _lastMatingEndTime
    --宠物底图
    local _petMutationLevel = PetManager.GetMutationLevel(_applyInfo.templatePetInfo.genes)
    obj:GetChild("Img_MyPet"):GetController("level"):SetSelectedIndex(_petMutationLevel - 1)
    obj:GetChild("Img_MyPet"):GetChild("frame").url = PetManager.GetMutationLevelFrameIcon(_petMutationLevel)
    --显示宠物模型
    local _parentGO = obj:GetChild("Img_MyPet"):GetChild("Model_Pet")
    if this.petAppliesModelInfo[_applyIndex] == nil then
        this.petAppliesModelInfo[_applyIndex] = {}
    end
    if this.petAppliesModelInfo[_applyIndex].modelGO and this.petAppliesModelInfo[_applyIndex].petId == _applyInfo.templatePetInfo.petId then
        PetManager.PetModelRefresh(this.petAppliesModelInfo[_applyIndex], _applyInfo.templatePetInfo.genes, false)
    else
        this.removePetAppliesModelByIndex(_applyIndex)
        resMgr:LoadModelPrefab(PetManager.PetModelPrefab, function(go)
            this.petAppliesModelInfo[_applyIndex].modelGO = newObject(go)

            local com = this.petAppliesModelInfo[_applyIndex].modelGO:GetComponent("SkeletonGraphic")

            if this.petAppliesModelInfo[_applyIndex].modelGO and com then
                com.material = resMgr.Pet_Copy_Mat
                com.material:SetFloat("_StencilComp", 8)
                com.material:SetFloat("_Stencil", 1);
            end
            this.petAppliesModelInfo[_applyIndex].parentGO = _parentGO
            local _modelWrapper = this.petAppliesModelInfo[_applyIndex].modelWrapper
            this.petAppliesModelInfo[_applyIndex].modelWrapper = GoWrapper.New()
            this.petAppliesModelInfo[_applyIndex].petId = _applyInfo.templatePetInfo.petId
            PetManager.PetModelFirstSet(this.petAppliesModelInfo[_applyIndex], _applyInfo.templatePetInfo.genes, false, Vector3.New(0, 0, 0), Vector3.New(0.55, 0.55, 1))
            if _modelWrapper then
                _modelWrapper:Dispose()
            end
        end)
    end
end
--接受宠物拟变申请
function this:onClickConfirm()
    local _applyInfo = logicMgr.PetManager.applies[PetManager.SelectedOthersApplyIndex]
    PetHandler.ReqAgreeMating(_applyInfo.templatePetInfo.petId, _applyInfo.mutatePetInfo.petId)
end
--拒绝宠物拟变申请
function this:onClickRefuse()
    local _applyInfo = logicMgr.PetManager.applies[PetManager.SelectedOthersApplyIndex]
    PetHandler.ReqRefuseMating(_applyInfo.templatePetInfo.petId, _applyInfo.mutatePetInfo.petId)
end

function this.onOthersApplyItemClick(context)
    local _obj = context.data
    local _index = this.List_OthersApply:GetChildIndex(_obj)
    local _applyInfo = this.othersApplyList[_index + 1]
    local _matingEndTime = PetManager.GetPetMatingEndTime(_applyInfo.templatePetInfo.petId)
    local _canMating = PetManager.CheckPetCanTemplate(_applyInfo.templatePetInfo)
    if _canMating and _matingEndTime == 0 then
        PetManager.SelectedOthersApplyIndex = _index + 1
        showUI(PanelNames.Page_PetApplyConfirm)
    else
        UISysTips.AddMsg(getLanguage("PetMating_CannotMating"))
    end
end

function this.onClickConfirm()
    local _applyInfo = logicMgr.PetManager.applies[PetManager.SelectedOthersApplyIndex]
    PetHandler.ReqAgreeMating(_applyInfo.templatePetInfo.petId, _applyInfo.mutatePetInfo.petId)
end
function this.onClickRefuse()
    local _applyInfo = logicMgr.PetManager.applies[PetManager.SelectedOthersApplyIndex]
    PetHandler.ReqRefuseMating(_applyInfo.templatePetInfo.petId, _applyInfo.mutatePetInfo.petId)
end

function this.onClickOrderByTime()
    this.showOthersApply()
end
function this.onClickOrderByFriend()
    if this.Btn_OrderByFriend.selected then
        this.othersApplyList = {}
        for _, applyInfo in ipairs(PetManager.applies) do
            if FriendManager.IsFriend(applyInfo.fromPlayerId) then
                table.insert(this.othersApplyList, applyInfo)
            end
        end
    else
        this.othersApplyList = PetManager.applies
    end
    this.showOthersApply()
end

function this.onClickRefuseAll()
    if #PetManager.applies > 0 then
        showUI(PanelNames.Page_PetApplyRefuseAll)
    end
end

function UIPet.onShowMyApplyPage()
    if table.getn(PetManager.myApply) > 0 or table.getn(PetManager.OtherPetInfo) > 0 then
        showUI(PanelNames.Page_PetApplyMyRequest)
    else
        UISysTips.AddMsg(getLanguage("PetApply_NoRequest"))
    end
end
--显示宠物模型
function this.removeMainPetModel()
    if this.mainPetModelInfo then
        if this.mainPetModelInfo.modelGO then
            destroyImmediate(this.mainPetModelInfo.modelGO)    
        end
        this.mainPetModelInfo.modelGO = nil
        this.mainPetModelInfo.parentGO = nil
        this.mainPetModelInfo.petId = nil
    end
end
function this.showMainPetModel()
    local _petInfo = PetManager.GetPetInfoByPetId(PetManager.CurrentPetId)
    if _petInfo and #_petInfo.genes == PetManager.PetPart.Ornament then
        this.Model_Pet.visible = true;
        if #PetManager.PetInfoList == 0 then
            this.ctrlNoPet.selectedIndex = 1
            obj:GetChild("PetListEmpty1"):GetChild("title").text = getLanguage("PetMain_NoPet")
            obj:GetChild("PetListEmpty2"):GetChild("title").text = getLanguage("PetFittingRoom_NoPet")
        else
            this.ctrlNoPet.selectedIndex = 0
        end
        if this.mainPetModelInfo.modelGO then
            this.mainPetModelInfo.petId = _petInfo.petId;
            PetManager.PetModelRefresh(this.mainPetModelInfo, _petInfo.genes, true)
        else
            this.removeMainPetModel()
            resMgr:LoadModelPrefab(PetManager.PetModelPrefab, function(go)
                this.mainPetModelInfo.modelGO = newObject(go)

                local com = this.mainPetModelInfo.modelGO:GetComponent("SkeletonGraphic")

                if this.mainPetModelInfo.modelGO and com then
                    com.material = resMgr.Pet_Copy_Mat
                    com.material:SetFloat("_StencilComp", 8)
                    com.material:SetFloat("_Stencil", 1);
                end

                this.mainPetModelInfo.parentGO = this.Model_Pet
                local _modelWrapper = this.mainPetModelInfo.modelWrapper
                this.mainPetModelInfo.modelWrapper = GoWrapper.New()
                this.mainPetModelInfo.petId = _petInfo.petId
                PetManager.PetModelFirstSet(this.mainPetModelInfo, _petInfo.genes, true, Vector3.New(0, 0, 0), Vector3.New(2.5, 2.5, 1))
                if _modelWrapper then
                    _modelWrapper:Dispose()
                end
            end)
        end
        for k, v in pairs(_petInfo.genes) do
            local go = this.PetPartsShow[k];
            local ctrlItem = CtrlManager.GetCtrl(PanelNames.PetPartItem);
            ctrlItem.initData(go, v);
        end
    else
        --没有宠物信息
        this.Model_Pet.visible = false;
    end
end
--试衣间
function this.onTryPart()
    beforeTabIndex = this.PetTabTypeController.selectedIndex
    this.CheckBodyController:SetSelectedIndex(1);
    this.ClickWeak:SetSelectedIndex(0)
    local _petInfo = PetManager.GetPetInfoByPetId(PetManager.CurrentPetId)

    this.selectedPetTab = PetTabType.TryPart;
    local genes = decodeJsonStrToTabel(G.dataTable["t_global"]["401"]["f_string_value"]);
    this.Model_Pet.visible = true;
    if _petInfo == nil then
        this.tryPartGenes = genes
        if not this.mainPetModelInfo.modelGO then
            this.removeMainPetModel()
            this.ctrlNoPet.selectedIndex = 0;
            resMgr:LoadModelPrefab(PetManager.PetModelPrefab, function(go)
                this.mainPetModelInfo.modelGO = newObject(go)

                local com = this.mainPetModelInfo.modelGO:GetComponent("SkeletonGraphic")

                if this.mainPetModelInfo.modelGO and com then
                    com.material = resMgr.Pet_Copy_Mat
                    com.material:SetFloat("_StencilComp", 8)
                    com.material:SetFloat("_Stencil", 1);
                end

                this.mainPetModelInfo.parentGO = this.Model_Pet
                local _modelWrapper = this.mainPetModelInfo.modelWrapper
                this.mainPetModelInfo.modelWrapper = GoWrapper.New()
                this.mainPetModelInfo.petId = 0
                PetManager.PetModelFirstSet(this.mainPetModelInfo, this.tryPartGenes, true, Vector3.New(0, 0, 0), Vector3.New(2.5, 2.5, 1))
                if _modelWrapper then
                    _modelWrapper:Dispose()
                end
            end)
        end
    else
        genes = clone(_petInfo.genes);
    end
    this.tryPartGenes = genes;
    this.refreshGroupState()
    this.changeTryPartListByType(1)
end

function this.refreshGroupState()
    local haveGroup = {}
    local choose = this.tryPartGroupIdx;
    for i = 1, #this.saveTryPartBtnGroup do
        local data = PetManager.getSaveTryPartDataGroup(i);
        local btn = this.saveTryPartBtnGroup[i];
        local btnController = btn:GetController("save");
        if (data ~= nil and table.getn(data) <= 0) or data == nil then
            btnController:SetSelectedIndex(0);
            haveGroup[i] = 0;
        else
            btnController:SetSelectedIndex(1);
            haveGroup[i] = 1;
        end
    end
    local curGenes = PetManager.getSaveTryPartDataGroup(choose);
    if (curGenes ~= nil and table.getn(curGenes) <= 0) or curGenes == nil then
        for i = 1, #haveGroup do
            if haveGroup[i] == 1 then
                choose = i;
                break ;
            end
        end

    end
    this.tryPartGroupIdx = choose;
    this.saveTryPartBtnGroup[choose].selected = true;
    this.clickTryPartGroup();
end

function this.changeTryPartListByType(type,isClick)
    if this.tryPartTypeId ~= type then
        if isClick then
            AudioManager.Play(4017)
        end
        this.tryPartListData = PetManager.GetAllPartsByType(type);
        table.sort(this.tryPartListData, function(a, b)
            return a.f_MutationLevel > b.f_MutationLevel;
        end);
        this.tryPartTypeId = type;
        this.tryPartTypeName.text = getLanguage("PetPart" .. type);
        this.tryPartList.numItems = #this.tryPartListData;
        this.refreshTryPetModel();
    end
end

function this.rendererTryPartItem(idx, obj)
    local data = this.tryPartListData[idx + 1];
    if this.checkChoose(data.f_GeneId) then
        obj.selected = true;
    else
        obj.selected = false;
    end
    local item = obj:GetChild("item");
    local ctrlItem = CtrlManager.GetCtrl(PanelNames.PetPartItem);
    ctrlItem.initData(item, data.f_GeneId, function(cfg,go)
        this.clickTryPart(cfg)
    end);
end

function this.clickTryPart(data)
    if data.f_ChromosomeId == nil then
        return ;
    end
    if this.tryPartGenes[data.f_ChromosomeId] == nil then
        this.tryPartGenes[data.f_ChromosomeId] = {};
    end
    this.tryPartGenes[data.f_ChromosomeId] = data.f_GeneId;
    this.refreshTryPetModel();
end

function this.refreshTryPetModel()
    for k, v in pairs(this.tryPartGenes) do
        local go = this.PetParts[k];
        local itemCfg = G.dataTable["t_elvesgene"][tostring(v)];
        go:GetChild("icon").url = "ui://PetAtlas/" .. itemCfg.f_ResId;
        if this.tryPartTypeId == itemCfg.f_ChromosomeId then
            go.selected = true;
        else
            go.selected = false;
        end
        go.onClick:Clear();
        go.onClick:Add(function()
            this.changeTryPartListByType(itemCfg.f_ChromosomeId,true)
        end)
    end
    PetManager.PetModelRefresh(this.mainPetModelInfo, this.tryPartGenes, true)
    HelperFunc.ListTranstionPlay(this.tryPartList)
end

function this.clickTryPartGroup(idx)
    local idx = this.tryPartGroupIdx;
    local curGeneData = PetManager.getSaveTryPartDataGroup(idx);
    if (curGeneData ~= nil and table.getn(curGeneData) == 0) or curGeneData == nil then
        curGeneData = this.tryPartGenes;
    end
    this.tryPartGenes = clone(curGeneData);
    this.refreshTryPetModel();
end

--保存当前试穿组
function this.saveTryPartData()
    this.tryPartCallBack = function()
        PetManager.setSaveTryPartDataGroup(this.tryPartGroupIdx, this.tryPartGenes)
    end
    PetHandler.ReqPetTryPartUpdate(this.tryPartGroupIdx, this.tryPartGenes);

end

--删除当前试穿组
function this.deleteTryPartData()
    this.tryPartCallBack = function()
        PetManager.setSaveTryPartDataGroup(this.tryPartGroupIdx, {});
    end
    PetHandler.ReqPetTryPartUpdate(this.tryPartGroupIdx, {});
end

function this.checkChoose(id)
    for i, v in pairs(this.tryPartGenes) do
        if v == id then
            return true;
        end
    end
    return false;
end

function this.saveTryPartCallBack()
    if this.tryPartCallBack then
        this.tryPartCallBack()
        this.refreshGroupState()
        this.tryPartCallBack = nil;
    end
end
--魂印
function this.FreshAttr()
    local _petInfo = PetManager.GetPetInfoByPetId(PetManager.CurrentPetId)
    if _petInfo and #_petInfo.genes == PetManager.PetPart.Ornament then
        this.attrHavePetCtrl.selectedIndex = 1
        resMgr:LoadModelPrefab(PetManager.PetModelPrefab, function(go)
            if this.attrmodelGO then
                destroy(this.attrmodelGO)
                this.attrmodelGO = nil
            end
            this.attrmodelGO = newObject(go)
            local com = this.attrmodelGO:GetComponent("SkeletonGraphic")
            if this.attrmodelGO and com then
                com.material = resMgr.Pet_Copy_Mat
                com.material:SetFloat("_StencilComp", 8)
                com.material:SetFloat("_Stencil", 1);
            end
            this.attrmodelGO:AddComponent(TCanvas)
            this.attrmodelGO:AddComponent(TChangeSortingOrder)
            if not this.attrWra then
                this.attrWra = GoWrapper.New()
            end
            this.attrWra:SetWrapTarget(this.attrmodelGO, false)
            this.attrGra:SetNativeObject(this.attrWra)
            Util.Lua_SetLocalPositionXYZ( this.attrmodelGO, 0, 0,0)
            Util.Lua_SetLocalScaleXYZ( this.attrmodelGO, 2.5, 2.5, 1)
            local _skeletonGraphic = this.attrmodelGO:GetComponent("SkeletonGraphic")
            logicMgr.PetManager.changePetSlot(_skeletonGraphic, _petInfo.genes,true)
        end)
    else
        this.attrHavePetCtrl.selectedIndex = 0
    end
end

function this.FreshSkill()
    this.PetTabTypeController.selectedIndex = 5
    this.choosePartCtrl.selectedIndex = 0
    this.FreshAttr()
    attrSkillList:SetVirtualAndLoop();
    attrSkillList.itemRenderer = this.RenderSkillItem
    this.UpLvFresh()
    attrSkillList.scrollPane.onScroll:Remove(this.DoSpecial)
    attrSkillList.scrollPane.onScrollEnd:Remove(this.onScrollEnd)
    attrSkillList.onClickItem:Remove(this.scrollToItem)
    attrSkillList.scrollPane.onScroll:Add(this.DoSpecial);
    attrSkillList.scrollPane.onScrollEnd:Add(this.onScrollEnd);
    attrSkillList.onClickItem:Add(this.scrollToItem)
    this.playUIMusic = false
    this.DoSpecial()
    this.onScrollEnd()
end

function this.UpLvFresh(msg)
    this.clickTick = 0
    if logicMgr.PetManager.petPartAllLv > 0 then
        attrReset.visible = true
    else
        attrReset.visible = false
    end
    attrSkillList.numItems  = table.getn(logicMgr.PetManager.petPartSkillByGroup)
    this.attrSkillTip.text = string.format(getLanguage("PetTips_10001"),logicMgr.PetManager.petPartAllLv)
    this.ClickAttrPart(this.choosePartCtrl.selectedIndex + 1)
    for k,v in pairs(this.attrPetParts) do
        local partCfg = logicMgr.PetManager.GetCurPartdata(k)
        v.ctrl.selectedIndex = 1
        v.lv.text = partCfg.f_AttributeLevel
    end
    if msg then
        Util.PlayAction(this.attrPetParts[this.choosePartCtrl.selectedIndex + 1].anim,"idle",false);
        this.onScrollEnd()
        this.petPartLvUpList.itemRenderer = this.UpItem
        this.petPartLvUpList.numItems = 1
        utimer.delayCall(function()
            this.petPartLvUpCtrl.selectedIndex = 1
        end,300)
    end
end

function this.UpItem(idx,obj)
    local icon = obj:GetChild("btn_skill"):GetChild("n3"):GetChild("Icon")
    local lv = obj:GetChild("btn_skill"):GetChild("text_level")
    local improveObj = obj:GetChild("com_improve")
    local attrName = improveObj:GetChild("text_herotype")
    local attrBeVal = improveObj:GetChild("text_numBefore")
    local attrAfVal = improveObj:GetChild("text_numAfter")
    local lvObj = obj:GetChild("com_levelup")
    local lvName = lvObj:GetChild("text_herotype")
    local beforeLv = lvObj:GetChild("text_numBefore")
    local afterLv = lvObj:GetChild("text_numAfter")
    local cfg = logicMgr.PetManager.GetCurPartdata(this.choosePartCtrl.selectedIndex + 1)
    local skillCtrl = obj:GetController("SkillShow")
    local skillTitle = obj:GetChild("text_numBefore")
    local skilltip = obj:GetChild("SkillTips")
    local skillobj = obj:GetChild("n12")
    local skillIcon = skillobj:GetChild("Mask"):GetChild("Icon")
    local skillName = skillobj:GetChild("SkillName")
    local skillLv = skillobj:GetChild("SkillLevel")
    local skillCfg = PetManager.GetCurSkill()
    if skillCfg then
        skillCtrl.selectedIndex = 1
        local skillData = G.dataTable["t_skillshow"][tostring(skillCfg.f_PetSkill)]
        skillIcon.url = "ui://SkillAtlas/" .. skillData.f_SkillIcon
        skillName.text = getLanguage(skillData.f_SkillName)
        skillLv.text = string.format(getLanguage("WeaponSkillText1"),math.ceil(skillCfg.f_Id / 6))
        skilltip.text = getLanguage(skillData.f_Desc)
        if math.ceil(skillCfg.f_Id / 6) == 1 then
            skillTitle.text = string.format(getLanguage("PetTips_10005"),logicMgr.PetManager.petPartAllLv)
        else
            skillTitle.text = string.format(getLanguage("PetTips_10006"),logicMgr.PetManager.petPartAllLv)
        end
    else
        skillCtrl.selectedIndex = 0
    end
    icon.url = "ui://UIPet/pet_hunyin_icon_"..(this.choosePartCtrl.selectedIndex+1)
    lv.text = cfg.f_AttributeLevel.."/30"
    attrName.text = logicMgr.EquipManager.GetAttrName(cfg.f_AttributeType)
    local beCfg = logicMgr.PetManager.GetCurPartdata(this.choosePartCtrl.selectedIndex + 1,true)
    attrBeVal.text = logicMgr.EquipManager.GetAttrValue(beCfg.f_AttributeType,beCfg.f_AttributeValue)
    attrAfVal.text = logicMgr.EquipManager.GetAttrValue(cfg.f_AttributeType,cfg.f_AttributeValue)
    lvName.text = getLanguage("Sys_HeroLevel")
    beforeLv.text = beCfg.f_AttributeLevel
    afterLv.text = cfg.f_AttributeLevel
    local taData = {["beforeId"] = beCfg.ID,["curId"] = cfg.ID,["attrPartId"] = cfg.f_PetAttributeId,["attrLv"] = cfg.f_AttributeLevel}
    TAManager.TrackByDictionary("petPartsAttrUp", taData)
end

function this.DoSpecial()
    this.dataIndex = 3
    local viewWidth = attrSkillList.scrollPane.posX + attrSkillList.viewWidth /2
    for i= 0,attrSkillList.numChildren -1 do
        local obj = attrSkillList:GetChildAt(i)
        local itemWidth = obj.x + obj.width / 2
        local distance = math.abs(viewWidth - itemWidth)
        local chooseCtrl = obj:GetController("c1")
        chooseCtrl.selectedIndex = 0
        if distance > obj.width*3 then
            obj:SetScale(1,1)
        else
            local changeScale = 1 + (1 - distance / obj.width) * 0.2;
            if changeScale > 1.1 then
                this.dataIndex = attrSkillList:ChildIndexToItemIndex(i)+1
                chooseCtrl.selectedIndex = 1
            end
            obj:SetScale(changeScale, changeScale);
        end
    end
end

function this.scrollToItem(evt)
    local go = evt.data
    local midX = attrSkillList.scrollPane.posX + attrSkillList.viewWidth / 2
    if go.x > midX then
        attrSkillList.scrollPane:ScrollRight(1, true)
    else
        attrSkillList.scrollPane:ScrollLeft(1, true)
    end
end

function this.onScrollEnd()
    if this.playUIMusic then
        AudioManager.Play(4016)
    end
    this.playUIMusic = true
    local id = logicMgr.PetManager.petPartSkillByGroup[this.dataIndex].f_Id;
    local skillId = logicMgr.PetManager.petPartTBSkill[tostring(id)].f_PetSkill
    this.attrSkillDec.text = getLanguage(G.dataTable["t_skillshow"][tostring(skillId)].f_Desc)
end

function this.RenderSkillItem(idx,obj)
    local data = logicMgr.PetManager.petPartSkillByGroup[idx + 1]
    local skillName = obj:GetChild("SkillName")
    local lockCtrl = obj:GetController("c2")
    local lvLvmit = obj:GetChild("LockText")
    local icon = obj:GetChild("Mask"):GetChild("Icon")
    local skillLv = obj:GetChild("SkillLevel")
    if logicMgr.PetManager.petPartAllLv >= data.f_PetAttributeTotalLevel then
        lockCtrl.selectedIndex = 0
    else
        lockCtrl.selectedIndex = 1
        lvLvmit.text = data.f_PetAttributeTotalLevel
    end
    local skillData = G.dataTable["t_skillshow"][tostring(data.f_PetSkill)]
    icon.url = "ui://SkillAtlas/" .. skillData.f_SkillIcon
    skillName.text = getLanguage(skillData.f_SkillName)
    skillLv.text = string.format(getLanguage("WeaponSkillText1"),math.ceil(data.f_Id / 6))
    obj:SetPivot(0.5, 0.5);
end

function this.ClickAttrPart(index,isClick)
    local partCfg,afterCfg = logicMgr.PetManager.GetCurPartdata(index)
    this.petLvIcon.url = "ui://UIPet/pet_hunyin_icon_"..(this.choosePartCtrl.selectedIndex+1)
    this.attrPartLevel.text = string.format(getLanguage("GuildInvestment_1119"),partCfg.f_AttributeLevel)
    this.attrName.text = logicMgr.EquipManager.GetAttrName(partCfg.f_AttributeType)
    this.attrBeVal.text = logicMgr.EquipManager.GetAttrValue(partCfg.f_AttributeType,partCfg.f_AttributeValue)
    if isClick then
        AudioManager.Play(4015)
    end
    if partCfg.f_GrowthCost ~= "" then
        petPartLvMaxCtrl.selectedIndex = 0
        clickPartNeedItemId = partCfg.f_GrowthCost[1]
        this.attrItemIcon.url = logicMgr.ItemManager.GetItemIconPath(clickPartNeedItemId)
        local itemNum= logicMgr.ItemManager.getItemCountbyModelId(clickPartNeedItemId)
        local costNumStr = getNumString(itemNum)
        if  itemNum < partCfg.f_GrowthCost[2] then
            costNumStr = string.TextColor(costNumStr, "#FF0000");
        end
        this.attrItemNum.text = costNumStr .. "/" ..partCfg.f_GrowthCost[2]
        this.attrAfVal.text = logicMgr.EquipManager.GetAttrValue(afterCfg.f_AttributeType,afterCfg.f_AttributeValue)
        if logicMgr.PetManager.petPartAllLv >= partCfg.f_NeedTotalLevel then
            this.petPartLvShowCtrl.selectedIndex = 1
        else
            this.petPartLvShowCtrl.selectedIndex = 0
            this.petpartLvTip.text = string.format(getLanguage("PetTips_10004"),partCfg.f_NeedTotalLevel)
        end
    else
        petPartLvMaxCtrl.selectedIndex = 1
        this.petPartLvShowCtrl.selectedIndex = 1
    end
end

function this.AttrUp()
    local partId = this.choosePartCtrl.selectedIndex+1
    local curCfg = logicMgr.PetManager.GetCurPartdata(partId)
    local itemNum= logicMgr.ItemManager.getItemCountbyModelId(clickPartNeedItemId)
    if itemNum >= curCfg.f_GrowthCost[2] then
        if logicMgr.PetManager.petPartAllLv >= curCfg.f_NeedTotalLevel then
            -- 弱网连点限制
            local currTick = HelperFunc.GetServerTime()
            if currTick - this.clickTick > 1 then
                this.clickTick = currTick
                PetHandler.ReqUpLv(partId,curCfg.f_AttributeLevel)
            end
        else
            UISysTips.AddMsg(string.format(getLanguage("PetTips_10004"),curCfg.f_NeedTotalLevel))
        end
    else
        UISysTips.AddMsg(string.format(getLanguage("Character_Tips19"),logicMgr.ItemManager.GetItemName(clickPartNeedItemId)))
    end
end

function this.AttrReset()
    if logicMgr.PetManager.petPartAllLv > 0 then
        local needNum = G.dataTable["t_global"]["511"].f_int_value
        local num =  logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.GOLD)
        local pop = CtrlManager.GetCtrl(PanelNames.UICommonPop)
        pop.Init("109",function(b)
            if b then
                if num >= needNum then
                    PetHandler.ReqPartReset()
                else
                   UISysTips.AddMsg(getLanguage("Character_Tips7"))
                end
            end
        end,needNum)
    end
end

function this.GoSource()
    this.sourceCtrl.selectedIndex = 1
    this.UpdateSource()
end

function this.UpdateSource()
    logicMgr.ItemManager.updateSourceUI(this.sourceUIobj, {clickPartNeedItemId}, function()
        this.sourceCtrl.selectedIndex = 0
    end, function()
        this.OnDisable()
        closeUI(PanelNames.UIPet)
    end);
end

return UIPet